<template>
  <div class="role-management-page">
    <el-card class="main-card">
      <template #header>
        <div class="card-header">
          <span>角色管理</span>
          <div class="actions">
            <el-button type="primary" :icon="Plus" @click="handleAddRole">添加角色</el-button>
            <el-button type="success" :icon="Refresh" @click="handleRefresh">刷新列表</el-button>
          </div>
        </div>
      </template>

      <div class="search-container">
        <el-form :inline="true" :model="searchForm">
          <el-form-item label="角色名称">
            <el-input v-model="searchForm.roleName" placeholder="请输入角色名称" clearable @keyup.enter="handleSearch" style="width: 200px" />
          </el-form-item>
          <el-form-item label="角色编码">
            <el-input v-model="searchForm.roleCode" placeholder="请输入角色编码" clearable @keyup.enter="handleSearch" style="width: 200px" />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 200px">
              <el-option label="启用" :value="1" />
              <el-option label="禁用" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
            <el-button :icon="Refresh" @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <div class="table-container">
        <el-table :data="roleList" v-loading="loading" border empty-text="暂无角色数据" height="100%">
          <el-table-column prop="roleCode" label="角色编码" min-width="150" />
          <el-table-column prop="roleName" label="角色名称" min-width="150" />
          <el-table-column prop="description" label="描述" min-width="200" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="row.status === 1 ? 'success' : 'danger'">{{ row.status === 1 ? '启用' : '禁用' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="sortOrder" label="排序" width="80" />
          <el-table-column prop="createTime" label="创建时间" width="180" class-name="create-time-column">
            <template #default="{ row }">{{ formatDateTime(row.createTime) }}</template>
          </el-table-column>
          <el-table-column label="操作" width="340" fixed="right" class-name="action-column">
            <template #default="{ row }">
              <el-button type="primary" size="small" :icon="Edit" @click="handleEdit(row)">编辑</el-button>
              <el-button type="warning" size="small" :icon="Setting" @click="handleAssignMenus(row)">分配权限</el-button>
              <el-button type="danger" size="small" :icon="Delete" @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- Dialogs -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="600px" @close="handleDialogClose">
      <el-form :model="roleForm" :rules="roleRules" ref="roleFormRef" label-width="100px">
        <el-form-item label="角色编码" prop="roleCode">
          <el-input v-model="roleForm.roleCode" placeholder="请输入角色编码" :disabled="isEdit" />
        </el-form-item>
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleForm.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="roleForm.description" type="textarea" :rows="3" placeholder="请输入角色描述" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="roleForm.status">
            <el-radio :value="1">启用</el-radio>
            <el-radio :value="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序" prop="sortOrder">
          <el-input-number v-model="roleForm.sortOrder" :min="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">{{ isEdit ? '更新' : '创建' }}</el-button>
      </template>
    </el-dialog>

    <el-dialog title="分配菜单权限" v-model="permissionDialogVisible" width="500px" @close="handlePermissionDialogClose">
      <el-tree
        ref="menuTreeRef"
        :data="menuTreeData"
        :props="{ label: 'name', children: 'children' }"
        node-key="id"
        show-checkbox
        default-expand-all
        :default-checked-keys="selectedMenuIds"
      />
      <template #footer>
        <el-button @click="permissionDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSavePermissions" :loading="permissionSubmitting">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Refresh, Search, Edit, Delete, Setting } from '@element-plus/icons-vue';
import { getRoleListApi, createRoleApi, updateRoleApi, deleteRoleApi, getRoleMenusApi, assignRoleMenusApi } from '@/api/role';
import { getAllMenusApi } from '@/api/menu';

// Interfaces
interface Role {
  id?: number;
  roleCode: string;
  roleName: string;
  description?: string;
  status: number;
  sortOrder: number;
  createTime?: string;
  updateTime?: string;
}

// Reactive state
const loading = ref(false);
const submitting = ref(false);
const permissionSubmitting = ref(false);
const roleList = ref<Role[]>([]);
const dialogVisible = ref(false);
const permissionDialogVisible = ref(false);
const dialogTitle = ref('');
const isEdit = ref(false);
const roleFormRef = ref();
const menuTreeRef = ref();
const currentRole = ref<Role | null>(null);
const menuTreeData = ref([]);
const selectedMenuIds = ref<number[]>([]);

const searchForm = ref({
  roleName: '',
  roleCode: '',
  status: undefined as number | undefined,
});

const roleForm = ref<Role>({
  roleCode: '',
  roleName: '',
  description: '',
  status: 1,
  sortOrder: 0,
});

const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});

const roleRules = {
  roleCode: [{ required: true, message: '请输入角色编码', trigger: 'blur' }],
  roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
};

// Computed properties - 移除前端筛选，直接使用后端返回的数据

// Methods
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '-';
  return new Date(dateTime).toLocaleString('zh-CN');
};

const resetForm = () => {
  roleForm.value = { roleCode: '', roleName: '', description: '', status: 1, sortOrder: 0 };
  if (roleFormRef.value) {
    roleFormRef.value.clearValidate();
  }
};

const loadRoles = async (searchParams?: any) => {
  loading.value = true;
  try {
    const params = {
      page: pagination.value.currentPage,
      size: pagination.value.pageSize,
      ...searchParams
    };
    const res = await getRoleListApi(params);
    // 兼容ResponseEntity<List<Role>>直接返回数组
    if (Array.isArray(res)) {
      roleList.value = res;
      pagination.value.total = res.length;
    } else if (res.data && Array.isArray(res.data)) {
      roleList.value = res.data;
      pagination.value.total = res.data.length;
    } else if (res.data && res.data.records) {
      roleList.value = res.data.records;
      pagination.value.total = res.data.total || res.data.records.length;
    } else {
      roleList.value = [];
      pagination.value.total = 0;
    }
  } catch (error) {
    ElMessage.error('获取角色列表失败');
    roleList.value = [];
  } finally {
    loading.value = false;
  }
};

const loadMenuTree = async () => {
  try {
    const res = await getAllMenusApi();
  menuTreeData.value = Array.isArray(res) ? res : (res.data || []);
  } catch (error) {
    ElMessage.error('获取菜单树失败');
  }
};

const handleSearch = () => {
  pagination.value.currentPage = 1;
  const searchParams = {
    roleName: searchForm.value.roleName || undefined,
    roleCode: searchForm.value.roleCode || undefined,
    status: searchForm.value.status
  };
  loadRoles(searchParams);
};

const handleReset = () => {
  searchForm.value = { roleName: '', roleCode: '', status: undefined };
  pagination.value.currentPage = 1;
  loadRoles();
};

const handleSizeChange = (val: number) => {
  pagination.value.pageSize = val;
  pagination.value.currentPage = 1;
  handleSearch();
};

const handleCurrentChange = (val: number) => {
  pagination.value.currentPage = val;
  handleSearch();
};

const handleAddRole = () => {
  dialogTitle.value = '添加角色';
  isEdit.value = false;
  resetForm();
  dialogVisible.value = true;
};

const handleRefresh = () => {
  loadRoles();
};

const handleEdit = (role: Role) => {
  dialogTitle.value = '编辑角色';
  isEdit.value = true;
  Object.assign(roleForm.value, role);
  dialogVisible.value = true;
};

const handleDelete = async (role: Role) => {
  await ElMessageBox.confirm(`确定要删除角色 ${role.roleName} 吗？`, '提示', { type: 'warning' });
  try {
    await deleteRoleApi(role.id!);
    ElMessage.success('删除成功');
    loadRoles();
  } catch (error) {
    ElMessage.error('删除失败');
  }
};

const handleAssignMenus = async (role: Role) => {
  currentRole.value = role;
  await loadMenuTree();
  try {
    const res = await getRoleMenusApi(role.id!);
  selectedMenuIds.value = Array.isArray(res) ? res : (res.data || []);
  } catch (error) {
    selectedMenuIds.value = [];
  }
  permissionDialogVisible.value = true;
};

const handleSavePermissions = async () => {
  if (!currentRole.value) return;
  permissionSubmitting.value = true;
  try {
    const checkedKeys = menuTreeRef.value.getCheckedKeys();
    const halfCheckedKeys = menuTreeRef.value.getHalfCheckedKeys();
    const allCheckedKeys = [...checkedKeys, ...halfCheckedKeys];
    await assignRoleMenusApi(currentRole.value.id!, allCheckedKeys);
    ElMessage.success('权限分配成功');
    permissionDialogVisible.value = false;
  } catch (error) {
    ElMessage.error('权限分配失败');
  } finally {
    permissionSubmitting.value = false;
  }
};

const handleSubmit = () => {
  roleFormRef.value.validate(async (valid: boolean) => {
    if (!valid) return;
    submitting.value = true;
    try {
      const api = isEdit.value ? updateRoleApi : createRoleApi;
      await api(roleForm.value);
      ElMessage.success(isEdit.value ? '更新成功' : '创建成功');
      dialogVisible.value = false;
      loadRoles();
    } catch (error) {
      ElMessage.error(isEdit.value ? '更新失败' : '创建失败');
    } finally {
      submitting.value = false;
    }
  });
};

const handleDialogClose = () => {
  resetForm();
};

const handlePermissionDialogClose = () => {
  currentRole.value = null;
  selectedMenuIds.value = [];
};

onMounted(() => {
  loadRoles();
});
</script>

<style lang="less" scoped>
.role-management-page {
  height: 100%;
  padding: 20px;
  box-sizing: border-box;
}

.main-card {
  height: 100%;
  display: flex;
  flex-direction: column;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
  }

  :deep(.el-card__header) {
    flex-shrink: 0;
  }

  :deep(.el-card__body) {
    flex: 1;
    display: flex;
    flex-direction: column;
    min-height: 0;
    padding: 20px;
  }
}

.search-container {
  flex-shrink: 0;
  margin-bottom: 16px;
}

.table-container {
  flex: 1;
  min-height: 0;
  overflow: hidden; /* For el-table height="100%" to work */
}

.pagination-container {
  flex-shrink: 0;
  padding-top: 16px;
  display: flex;
  justify-content: flex-end;
}

:deep(.create-time-column) {
  border-left: 1px solid #ebeef5;
}

:deep(.action-column) {
  border-left: 1px solid #ebeef5;
}
</style>